<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ws</title>
</head>
<body>
<form onsubmit="return false">
    <textarea name="msgs" id="msgs" cols="60" rows="10"></textarea>
    <hr/>
    <input type="text" name="msg"/>
    <input type="button" name="send" value="send" onclick="sendMsg(this)"/>
</form>
<script type="text/javascript">
    let ws = null,tt = null;
    let lockRequest = false;
    let wsUrl = "ws://localhost:9000/hello";
    let text = document.getElementsByName('msgs')[0];

    // 心跳检测
    let heartCheck = {
        timeOut: 3000,
        timeOutObj: null,
        serverTimeoutObject: null,
        start: function () {
            let self = this;
            this.timeOutObj && clearTimeout(this.timeOutObj);
            this.serverTimeoutObject && clearTimeout(this.serverTimeoutObject);
            this.timeOutObj = setTimeout(function () {
                // 发送一个心跳包
                // doSomething
                this.serverTimeoutObject = setTimeout(function () {
                    ws.close();
                },this.timeOut)

            }, this.timeOut);
        }
    };

    if ('WebSocket' in window) {
        console.log("支持WebSocket！");
        try {
            createWebSocket();
        }catch (e) {
            reconnect(wsUrl);
        }
    }

    function createWebSocket() {
        ws = new WebSocket(`${wsUrl}`);
        init();
    }

    function reconnect(url) {
        if (lockRequest) {
            return;
        }
        lockRequest = true;
        tt && clearTimeout(tt);
        tt = setTimeout(function () {
            createWebSocket(url);
        }, 4000);
    }

    function init() {
        ws.onopen = function (ev) {
            text.value = '连接成功！';
            heartCheck.start();
        }
        ws.onclose = function (ev) {
            text.value = text.value + '\n连接关闭！';
        }
        ws.onmessage = function (ev) {
            text.value = text.value + '\n' + ev.data;
            console.log("数据接收成功：" + ev.data);
        }
    }
    function sendMsg(This) {
        ws.send(This.form['msg'].value);
    }

</script>
</body>
</html>